#include "mainHeader.h"
#include "createVFS.h"
char* createVFS(char *fileName,int fileLength)
{
	//ToDo insufficient memory availability test case
	if(fileLength<1 || fileLength>1024)
		return ERR_VFS_CREATE_04;
	fileLength=fileLength*1024;//multiplied by 1024 because input is in KB
	int maxFileDescriptors=2*fileLength/avgFileSizeInVFSInBytes; //2 because we have FDs created for directories as well
	int noOfBlocks=fileLength/maxBlockSize;
	FILE *fp=fopen(fileName,"r");
	if(fp!=NULL)
		return ERR_VFS_CREATE_01;
	if(strlen(fileName)>maxSizeOfVFSName)
		return ERR_VFS_CREATE_05;
	int i=0;
	for(;i<=strlen(fileName);i++)
	{
		if(fileName[i]=='/')
			return ERR_VFS_CREATE_03;
	}
	fp=fopen(fileName,"wb"); // creates the file
	if(fp==NULL)
		return ERR_VFS_CREATE_02;
	char *memory=(char*) malloc(fileLength);
	fwrite(memory,fileLength,1,fp); // allocates the size specified to the file
	meta *mh=(meta*) malloc(sizeof(meta));
	strcpy(mh->fileSystemLabel,fileName);
	mh->countOfFileDescriptors=0;
	mh->maxDescriptors=maxFileDescriptors;
	rewind(fp); // sets pointer to 0th byte
	long currentPos=ftell(fp); // gives current position
	fwrite(mh,sizeof(meta),1,fp); // adds meta header
	fclose(fp);
	fp=fopen(fileName,"r+b");
	fseek(fp,sizeof(meta),SEEK_SET);
	bitMap=(char*)malloc(sizeof(char)*noOfBlocks);
	int iterBlocks=0;
	for(;iterBlocks<noOfBlocks;iterBlocks++)
		bitMap[iterBlocks]='0'; // all blocks are initially free
	head *h=(head*)malloc(sizeof(char)*noOfBlocks+sizeof(descriptors)*maxFileDescriptors);
	h->desc=(descriptors*)malloc(sizeof(descriptors)*maxFileDescriptors);
	h->freeList=bitMap;
	fwrite(h,sizeof(char)*noOfBlocks+sizeof(descriptors)*maxFileDescriptors,1,fp);
	fseek(fp,sizeof(meta)+sizeof(descriptors)*maxFileDescriptors,SEEK_SET);
	fwrite(bitMap,sizeof(char)*noOfBlocks,1,fp);
	arr=(int*)malloc(sizeof(int)*noOfBlocks);
	int *blockPtr;
	iterBlocks=0;
	while(iterBlocks<noOfBlocks)
	{
		blockPtr=(int*)malloc(maxBlockSize);
		arr[iterBlocks++]=(int)ftell(fp);
		fseek(fp,sizeof(meta)+sizeof(descriptors)*maxFileDescriptors+sizeof(char)*noOfBlocks+maxBlockSize*(iterBlocks-1),SEEK_SET);
		fwrite(blockPtr,maxBlockSize,1,fp);
	}
	fwrite(arr,sizeof(arr),1,fp);
	mh=NULL;
	h=NULL;
	fclose(fp);
	return "SUCCESS";
}
